package com.zbw.printlibrary.util;



import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;



import java.util.List;

/**
 * JSON格式数据解析
 * Json Parser
 */
public class JsonAnalysisUtil {
	/**
	 * 解析数据，返回数据Bean对象
	 * parse string data and return bean
	 */
	public static <T> T getObjectByString(String result, Class<T> clazz) throws org.json.JSONException {
		if (clazz == null) {
			return null;
		}
		T obj = null;
		try {
			obj =JSONObject.parseObject(result, clazz);
		} catch (Exception e) {
			e.printStackTrace();
			throw new JSONException();
		}
		return obj;
	}
	
	/**
	 * 解析数据，返回数据Bean对象集合
	 * parse string data and return bean array
	 */
	public static <T> List<T> getObjectsByString(String result, Class<T> clazz) throws org.json.JSONException {
		if (clazz == null) {
			return null;
		}
		
		List<T> resultObj = null;
		
		try {
			resultObj = JSONObject.parseArray(result, clazz);
		} catch (Exception e) {
			e.printStackTrace();
			throw new JSONException();
		}

		return resultObj;
	}
	
	/**
	 * 将Object对象转成JSON格式的字符串
	 * convert object to json string
	 */
	public static String getJsonStringByObject(Object object) throws org.json.JSONException {
		String jsonStr = null;
		try {
//			jsonStr = JSONObject.toJSONString(object, false);
			int features = SerializerFeature.config(JSON.DEFAULT_GENERATE_FEATURE, SerializerFeature.WriteEnumUsingName, false);
			jsonStr = JSONObject.toJSONString(object,features, SerializerFeature.EMPTY);
		} catch (Exception e) {
			e.printStackTrace();
			throw new JSONException();
		}
		return jsonStr;
	}
}